package com.view.comp.SelfLabelingTextInput
{
	import flash.events.FocusEvent;
	
	import spark.components.TextInput;

	/**
	 * A text input that displays a gray label inside itself when it's empty.  When the user clicks in,
	 * the label disappears.  If the user exits the field and leaves it empty, the label reappears.
	 * 
	 * TODO: get the label color from a style instead of hard-coding it.
	 *
	 * @author Narciso Jaramillo <nj_flex@rictus.com>
	 */
	 
	public class LabeledInput  extends spark.components.TextInput
	{
		private var _textIsEmpty: Boolean = true;
		private var _label: String;
		
		/**
		 * The label to display when the text field is empty.
		 */
		public function get label(): String {
			return _label;
		}
		
		public function set label(value: String): void {
			_label = value;
			toolTip = value;
			updateContents();
		}
		
		[Bindable]
		override public function get text(): String {
			if (_textIsEmpty) {
				return "";
			}
			else {
				return super.text;
			}
		}
		
		override public function set text(value: String): void {
			if (value == "") {
				_textIsEmpty = true;
			}
			else {
				_textIsEmpty = false;
				super.text = value;
			}
			updateContents();
		}
		
		private function updateContents(): void {
			if (_textIsEmpty) {
				setStyle("color", 0xaaaaaa);
				super.text = _label;
			}
			else {
				setStyle("color", 0x000000);
			}
		}

		
		private function handleTextChange(event: Event): void {
			if (super.text == "") {
				_textIsEmpty = true;
			}
			else {
				_textIsEmpty = false;
			}
		}
		
		private function handleFocusIn(event: FocusEvent): void {
			if (_textIsEmpty) {
				super.text = "";
				setStyle("color", 0x000000);
			}
		}
		
		private function handleFocusOut(event: FocusEvent): void {
			updateContents();
		}
		
		override public function initialize(): void {
			super.initialize();
			addEventListener(Event.CHANGE, handleTextChange);
			addEventListener(FocusEvent.FOCUS_IN, handleFocusIn);
			addEventListener(FocusEvent.FOCUS_OUT, handleFocusOut);
			updateContents();
		}
	}
}